package com.atmilan.quartz.sync.pull.crmeb.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.atmilan.quartz.model.entity.crmeb.StoreOrder;
import com.atmilan.quartz.model.entity.sync.SyncOrderProduct;
import com.atmilan.quartz.model.entity.sync.SyncOrderStore;
import com.atmilan.quartz.model.result.CrmebOrderResult;
import com.atmilan.quartz.model.result.CrmebOrderResult.OrderProduct;
import com.atmilan.quartz.model.result.CrmebOrderResult.OrderStore;
import com.atmilan.quartz.model.vo.crmeb.StoreOrderInfoVo;
import com.atmilan.quartz.service.IStoreOrderInfoService;
import com.atmilan.quartz.service.IStoreOrderService;
import com.atmilan.quartz.sync.pull.crmeb.converter.SyncCrmebOrderConverter;
import com.atmilan.quartz.sync.pull.crmeb.service.ICrmebOrderSyncService;
import com.atmilan.quartz.sync.push.service.OrderPushService;
import com.atmilan.quartz.sync.service.ISyncOrderProductService;
import com.atmilan.quartz.sync.service.ISyncOrderStoreService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * x
 *
 * @author muyu.myw
 * @date 2020/10/9 16:59
 */
@Slf4j
@Service
public class CrmebOrderSyncServiceImpl implements ICrmebOrderSyncService {
    @Autowired
    ISyncOrderProductService syncOrderProductService;
    @Autowired
    ISyncOrderStoreService syncOrderStoreService;
    @Autowired
    SyncCrmebOrderConverter syncCrmebOrderConverter;
    @Autowired
    OrderPushService orderPushService;
    @Autowired
    IStoreOrderService storeOrderService;
    @Autowired
    IStoreOrderInfoService storeOrderInfoService;

    @Override
    public void syncCrmebOrder(Date startTime) {
        // 查询订单数据
        List<String> list = queryOrderIds(DateUtil.format(startTime, DatePattern.NORM_DATETIME_FORMAT));
        log.info("sync orderIds : {}", list);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        list.forEach(orderId -> {
            // 查一下id存不存在，存在就不处理了
            List<SyncOrderStore> orderList = syncOrderStoreService.list(Wrappers.<SyncOrderStore>lambdaQuery().eq(SyncOrderStore::getOuterOrderNo, orderId).eq(SyncOrderStore::getOrderSource, 1));

            if (CollectionUtils.isEmpty(orderList)) {
                CrmebOrderResult orderResult = getOrderDetail(orderId);
                // 发货人电话，地址是写在后台配置的
                if (orderResult != null && orderResult.getOrderInfo() != null) {
                    SyncOrderStore orderStore = syncCrmebOrderConverter.toOrderStoreModel(orderResult.getOrderInfo());
                    List<SyncOrderProduct> productList = syncCrmebOrderConverter.toOrderProductModelList(orderResult.getOrderInfo().getProductList());
                    if (CollectionUtils.isNotEmpty(productList)) {
                        orderStore.setStatus(0);
                        orderStore.setCreateTime(DateUtil.date());
                        orderStore.setEditTime(DateUtil.date());
                        syncOrderStoreService.save(orderStore);
                        productList.forEach(p -> {
                            p.setOuterOrderNo(orderStore.getOuterOrderNo());
                            p.setStatus(0);
                            p.setCreateTime(DateUtil.date());
                            p.setEditTime(DateUtil.date());
                        });
                        syncOrderProductService.saveBatch(productList);
                    }
                }
            }
        });

        // 同步完成, 推送订单
        pushOrder();
    }

    /**
     * 封装crme的查询订单接口
     * @Description:  
     * @author daigb 
     * @param @param startTime
     * @param @return
     * @return List<String>
     * @throws
     */
    private List<String> queryOrderIds(String startTime) {
        // 默认取全部订单
        if (StringUtils.isBlank(startTime)) {
            return null;
        }
        DateTime dt = DateUtil.parse(startTime, DatePattern.NORM_DATETIME_FORMAT);
        if (dt == null) {
            return null;
        }
        List<String> list = storeOrderService.queryOrderIds(dt);
        return list;
    }

    /**
     * 封装通过id查询订单数据
     * @Description:  
     * @author daigb 
     * @param @param orderId
     * @param @return
     * @return CrmebOrderResult
     * @throws
     */
    private CrmebOrderResult getOrderDetail(String orderId) {
        // 有可能不是唯一，要想办法处理下
        StoreOrder storeOrder = storeOrderService.getByOrderId(orderId);
        // 反推 - 临时过滤处理SourceCost为0的数据
        if (storeOrder == null || storeOrder.getSourceCost().compareTo(new BigDecimal("0")) == 0) {
            return null;
        }
        List<StoreOrderInfoVo> orderInfoVoList = storeOrderInfoService.getOrderListByOrderId(storeOrder.getId());
        if (CollectionUtils.isNotEmpty(orderInfoVoList)) {
            // 构造订单数据,懒得写bean了，先用json造一个调试吧
            CrmebOrderResult crmebOrderResult = new CrmebOrderResult();
            OrderStore orderStore = new OrderStore();
            
            orderStore.setOuterOrderNo(orderId);

            // 注意：推送给第三方的实际支付金额为第三方推送的成本总价(确认订单时，已经计算)
            // 第三方推送的成本总价 = 推送的成本价 * 商品数量
//            orderInfo.put("shippingFee", storeOrder.getPayPostage());
//            orderInfo.put("shipperName", "");
//            orderInfo.put("shipperPhone", "");
//            orderInfo.put("shipperAddress", "");
            orderStore.setPayPrice(storeOrder.getSourceCost());
            orderStore.setPayPostage(storeOrder.getPayPostage());
            orderStore.setPayType(storeOrder.getPayType());
            orderStore.setShippingType(storeOrder.getShippingType());
            orderStore.setAddress(storeOrder.getUserAddress());
            orderStore.setConsignee(storeOrder.getRealName());
            orderStore.setPhone(storeOrder.getUserPhone());
            orderStore.setOrderTime(storeOrder.getCreateTime().toString());
            orderStore.setPayTime(storeOrder.getPayTime().toString());

            // 设置sku信息
            List<OrderProduct> productList = new ArrayList<OrderProduct>();
            orderInfoVoList.forEach(info -> {
                OrderProduct skuInfo = new OrderProduct();
                skuInfo.setProductId(info.getInfo().getProductInfo().getBarCode());
                skuInfo.setSuk(info.getInfo().getProductInfo().getAttrInfo().getSuk());
                skuInfo.setQty(info.getInfo().getCartNum());
                skuInfo.setPrice(info.getInfo().getSourceCostPrice());
                skuInfo.setSupplySource(info.getInfo().getProductInfo().getMerId());
                
                productList.add(skuInfo);
            });
            orderStore.setProductList(productList);
            crmebOrderResult.setOrderInfo(orderStore);
            
            return crmebOrderResult;
        }
        
        return null;
    }

    /**
     * 推送订单
     */
    private void pushOrder() {
        // 1 从order表里查出待推送的订单
        // 2 组装数据推送
        List<SyncOrderStore> list = syncOrderStoreService.list(Wrappers.<SyncOrderStore>lambdaQuery().eq(SyncOrderStore::getStatus, 0));
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(orderStore -> {
                String result = orderPushService.pushOrder(orderStore);
                log.warn("pushOrder: " + result);
                //小黑库 - 更新订单
                updateSyncOrderStore(result, orderStore);
                //买手端 - 更新订单
                updateEbStoreOrder(result, orderStore);
            });
        }
    }

    /**
     * 小黑库 - 更新订单
     * @param result
     * @param orderStore
     */
    private void updateSyncOrderStore(String result, SyncOrderStore orderStore) {
        //解析数据
        if (StringUtils.isNotBlank(result)) {
            String status = JSONObject.parseObject(result).get("status").toString();
            orderStore.setStatus(status.equals("Success") ? 1:2);
            // 推送完更新订单状态
            if (status.equals("Success")) {
                JSONObject orderObj = (JSONObject) JSONObject.parseObject(result).get("order");
                String orderId = orderObj.get("order_id").toString();
                String orderSn = orderObj.get("order_sn").toString();

                orderStore.setPushOrderId(orderId);
                orderStore.setPushOrderSn(orderSn);
                orderStore.setEditTime(DateUtil.date());
                syncOrderStoreService.updateById(orderStore);
            }
        }
    }

    /**
     * 买手端 - 更新订单
     * @param result
     * @param orderStore
     */
    private void updateEbStoreOrder(String result, SyncOrderStore orderStore) {
        //解析数据
        if (StringUtils.isNotBlank(result)) {
            String status = JSONObject.parseObject(result).get("status").toString();
            String message = JSONObject.parseObject(result).get("message").toString();

            StoreOrder entity = new StoreOrder();
            LambdaUpdateWrapper<StoreOrder> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(StoreOrder::getOrderId, orderStore.getOuterOrderNo());
            entity.setPushStatus(status.equals("Success") ? 1:2);
            entity.setPushMessage(message);
            storeOrderService.update(entity, updateWrapper);
        }
    }
}
